const XTSerialize = {
	jsonType: "application/json",
	formType: "application/x-www-form-urlencoded",

	jsonTypeConfig() {
		return {
			"Content-Type": this.jsonType
		}
	},
	formTypeConfig() {
		return {
			"Content-Type": this.formType
		}
	},
	jsonHeader() {
		return {
			headers: this.jsonTypeConfig()
		}
	},
	formHeader() {
		return {
			headers: this.formTypeConfig()
		}
	},

	// 将对象进行序列化
	jsonToForm(data) {
		let str = '';
		for (let key in data) {
			str += `${key}=${encodeURIComponent(data[key])}&`;
		}
		return str.substring(0, str.length - 1);
	},

	arrayBufferType: "arraybuffer",
	setArrayBuffer(config) {
		config["responseType"] = this.arrayBufferType
	},

	binToArrayBuffer(res) { // 图片转换器
		// console.log("res", res);
		// const arrayBuffer = res
		const arrayBuffer = new Uint8Array(res) //将二进制数据保存为arrayBuffer格式
		console.log("arrayBuffer", arrayBuffer);
		return 'data:image/png;base64,' + uni.arrayBufferToBase64(arrayBuffer); //拼接前缀
	},
	binToArrayBuffer2(datas) {
		return 'data:image/png;base64,' + btoa(new Uint8Array(datas).reduce((datas, byte) => datas + String
			.fromCharCode(byte), ''))
	},
	arrayBufferToBase64(res) {
		return 'data:image/png;base64,' + uni.arrayBufferToBase64(res); //拼接前缀
	},

	blobToUrl(res) {
		let blob = new Blob([res], {
			type: 'image/jpeg'
		});
		const imageUrl = URL.createObjectURL(blob); //图片地址
		return imageUrl;
	},

	async getUrlFromResp(response) {
		// const response = await fetch(url);
		const blob = await response.blob();

		let imageUrl;
		// 将Blob对象转换为Base64编码字符串
		const reader = new FileReader();
		reader.onloadend = () => {
			const base64data = reader.result;
			imageUrl = base64data;
		};
		reader.readAsDataURL(blob);
		return imageUrl;
	},

	async fetchImage(srcUrl, data, rb) {
		try {
			let config = {
				url: srcUrl,
				method: 'GET',
				responseType: 'arraybuffer', // 指定返回类型为 ArrayBuffer
				header: {
					Accept: 'image/png',
				},
			}
			if (data) {
				config.data = data;
			}
			if (rb) {
				rb(config)
			}
			// console.log("config", config);
			const response = await uni.request(config);


			const base64 = uni.arrayBufferToBase64(response.data); // 将 ArrayBuffer 转成 Base64 字符串
			const imageUrl = 'data:image/png;base64,' + base64; // 填充到 img 组件的 src 属性
			return imageUrl;
		} catch (err) {
			console.error(err);
		}
	},

}

export {
	XTSerialize
}